# -*- coding: utf-8 -*-

import os
import platform
import re
import subprocess


class PingUtils:
    @classmethod
    def ping_server(cls, address, count=4):
        """
        使用系统ping命令测试服务器连通性。
        :param server_ip: 服务器IP地址或域名。
        :param count: 发送的ping请求数量，默认为4。
        :return: 返回ping测试的结果，包括丢失包的比例和最后一个返回的时间。
        """
        # 根据操作系统选择ping命令
        ping_cmd = ['ping', '-c', str(count), address]
        if platform.system().lower() == 'windows':
            ping_cmd = ['ping', '-n', str(count), address]
        print(ping_cmd)
        # 执行ping命令并获取输出
        result = subprocess.run(ping_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)

        # 解析输出来获取丢包率和时间
        loss_rate = None
        avg_time = None
        print(result.stdout)
        if result.returncode == 0:
            # 对于Linux系统
            if 'loss' in result.stdout:
                loss_match = re.search(r'(\d+)% packet loss', result.stdout)
                if loss_match:
                    loss_rate = float(loss_match.group(1))

                time_match = re.search(r'time=(\d+\.\d+) ms', result.stdout)
                if time_match:
                    avg_time = float(time_match.group(1))

            # 对于Windows系统
            elif 'Lost' in result.stdout or "丢失" in result.stdout:
                loss_match = re.search(r'Lost = (\d+) | 丢失 = (\d+)', result.stdout)
                if loss_match:
                    loss_rate = float(loss_match.group(1)) / count * 100

                time_match = re.search(r'Average = (\d+)ms', result.stdout)
                if time_match:
                    avg_time = float(time_match.group(1))

        return loss_rate, avg_time


if __name__ == '__main__':
    print("Python")

    server_address = '127.0.0.1'  # Google的公共DNS服务器
    loss_rate, avg_time = PingUtils.ping_server(server_address)
    if loss_rate is not None and avg_time is not None:
        print(f"{server_address} 的丢包率为 {loss_rate:.2f}%，平均响应时间为 {avg_time:.2f} ms。")
    else:
        print(f"{server_address} 无法ping通。")
